#include "log.h"
#include "task.h"
#include "applib/lib_syscall.h"
#include "tty.h"

int fork_test()
{
    int count = 300;
    int pid   = getpid();
    print_msg("current pid=%x", pid);
    pid = fork();
    if (pid < 0)
    {
        print_msg("create child proc failed.", 0);
    }
    else if (pid == 0)
    {
        count += 100;
        print_msg("child:%d", pid);
    }
    else
    {
        count -= 100;
        print_msg("child task id=%x", pid);
        print_msg("parent: %d", count);
    }
    for (;;)
    {
        print_msg("task_id = %x", pid);
        print_msg("count=%d", count);
        msleep(1000);
    }
    return 0;
}
void execve_test()
{
    int   count = 300;
    int   ret;
    char *name   = "/shell.elf";
    char *argv[] = {"arg0", "arg1", "arg2", "arg3", 0};
    char *env[]  = {"env0", "evn1", "env2", 0};
    int   pid    = fork();
    if (pid < 0)
    {
        print_msg("create child proc failed", 0);
    }
    else if (pid == 0)
    {
        count -= 200;
        print_msg1("child proc:id=%d,count=%d", getpid(), count);
        ret = execve(name, argv, env);
    }
    else
    {
        count += 200;
        print_msg1("parent proc:id=%d,count=%d", getpid(), count);
        print_msg("parent,create child proc success, child id=%d", pid);
    }

    for (;;)
    {
        // print_msg("execve_test task_id = %x",pid);
        // print_msg("execve_test count=%d",count);
        // msleep(1000);
    }
}
int execve_tty_test()
{
    for (int i = 0; i < TTY_NR; i++)
    {
        int pid = fork();
        if (pid < 0)
        {
            print_msg("create shell failed.", 0);
            break;
        }
        else if (pid == 0)
        {
            // char tty_num[5] = "tty:?";
            // tty_num[4]=i+'0';
            char tty_num[]               = "/dev/tty?";
            tty_num[sizeof(tty_num) - 2] = i + '0';
            char *argv[]                 = {tty_num, (char *)0};
            char *env[]                  = {"env0", "evn1", "env2", (char *)0};
            execve("shell.elf", argv, env);
            while (1)
            {
                // print_msg("execve_tty_test: child: tty:%x",getpid());
                msleep(1000);
            }
        }
        else
        {
            // print_msg("execve_tty_test:parent:pid=%x",pid);
        }
    }

    for (;;)
    {
        int status;
        wait(&status);
    }
    return 0;
}
int first_task_main(void)
{
    int a = 899;
    print_msg1("fist_task.c :hello world %d,%x,%c", 100, a, 'B');
    int count = 0;
    int pid   = getpid();
    print_msg("pid: %x", pid);
    // fork_test();
    // execve_test();
    execve_tty_test();
    for (;;)
    {
        // print_msg("first task main: %d ",count++);
        // sys_sleep(1000);
        // msleep(1000);
    }
    return 0;
}